package com.cnxjs.shs4et.interceptors;

import com.cnxjs.shs4et.common.JwtUtil;
import com.cnxjs.shs4et.entity.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


@Component
public class RoleBasedAuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user"); // 假设用户信息存储在会话中

        // 获取token
        String token = request.getHeader("Authorization");
        Map<String, Object> claims = JwtUtil.vertifyJWT(token);

        if (claims!=null) {
            // 根据角色和请求路径进行权限检查
            // 例如, 只有角色3和4可以访问 /user/update
            if (request.getRequestURI().contains("/user/update") && (claims.get("role").equals(3) || claims.get("role").equals(4))) {
                return true;
            }

            // ... 其他权限检查 ...

        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN); // 如果没有权限, 设置403禁止访问
        return false; // 返回false表示不继续向下执行
    }
}
